from flask import Blueprint,request,make_response,jsonify,redirect
import json, random, time, requests
from utils.myredis import r
from models.models import *

need_blue = Blueprint("needblue",__name__)

@need_blue.route("/getclose")
# 支付方式
def getclose():
    close = Close.query.all()
    print(close)
    lst = []
    for i in close:
        lst.append({
            "id":i.id,
            "name":i.name,
            "described":i.described
        })
    return jsonify({"code": 200, "msg": "获取成功","data":lst})

@need_blue.route("/getneed")
# 获取需求类型
def getneed():
    label = Need_kind.query.all()
    lists = []
    list_one = []
    for i in label:
        # 获取所有pid==0的数据
        if i.pid == 0:
            # 判断时候在list_one列表中
            if i.id not in list_one:
                # 将pid==0的数据加入到lists总
                lists.append({'id':i.id,'name':i.name,'son':[]})
                list_one.append([i.id])
    for j in label:
        for index,p in enumerate(lists):
            # 判断所有数据的pid是否等于lists中的id，将等于的数据加入到lists中的son中
            if j.pid == p['id']:
                lists[index]['son'].append({'id':j.id,'name':j.name,'tow_son':[]})
    for s in label:
        for index,p in enumerate(lists):
            aa = lists[index]['son']
            for indexa,a in enumerate(aa):
                if s.pid == a['id']:
                    aa[indexa]['tow_son'].append({'id':s.id,'name':s.name})
    return jsonify({"code":200,"data":lists})

@need_blue.route("/gettalents")
# 获取人才类型
def gettalents():
    label = Talents.query.all()
    lists = []
    list_one = []
    for i in label:
        # 获取所有pid==0的数据
        if i.pid == 0:
            # 判断时候在list_one列表中
            if i.id not in list_one:
                # 将pid==0的数据加入到lists总
                lists.append({'id':i.id,'name':i.name,'son':[]})
                list_one.append([i.id])
    for j in label:
        for index,p in enumerate(lists):
            # 判断所有数据的pid是否等于lists中的id，将等于的数据加入到lists中的son中
            if j.pid == p['id']:
                lists[index]['son'].append({'id':j.id,'name':j.name,'tow_son':[]})
    for s in label:
        for index,p in enumerate(lists):
            aa = lists[index]['son']
            for indexa,a in enumerate(aa):
                if s.pid == a['id']:
                    aa[indexa]['tow_son'].append({'id':s.id,'name':s.name})
    return jsonify({"code":200,"data":lists})

# 启动雪花算法
# snowflake_start_server --worker=1
import snowflake.client
def create_ordercode(tablename,count):
    # 雪花算法生成唯一id
    code = snowflake.client.get_guid()
    # 用redis解决始终回拨，根据key查询上一次存入的结果，
    # 和当前生成的对比，如果当前小于redis中存储的，说明发生时钟回拨
    # 先取
    value = r.str_get(tablename)
    # 判断是否存在
    if value:
        # 当前时间 小于 redis中存储的时间
        if int(code) < int(value):
            # 重新调用  雪花算法生成唯一id
            create_ordercode(tablename,count)
    # 把最后一次生成的存入redis
    r.set_str(tablename,code)
    # 取模获取列表
    number = hash(code)%int(count)
    print("number",number)
    if number == 0:
        return tablename,code
    else:
        return tablename + str(number),code

@need_blue.route("/setneed",methods=["POST"])
# 添加需求
def setneed():
    data = json.loads(request.data)
    closeid = data["closeid"]
    title = data["title"]
    described = data["described"]
    money = data["money"]
    userid = data["userid"]
    tablename, code = create_ordercode('Need', 3)
    print(tablename, code)
    # 转为表明
    tablename1 = globals().get(f'{tablename}')
    if not all([closeid,title,described,money,userid]):
        return jsonify({"code":400,"msg":"字段不能为空"})
    if closeid==1:
        needid = data["needid"]
        need = tablename1(code= code,closeid=closeid,title=title,described=described,needid=needid,money=money,userid=userid,status=1)
        db.session.add(need)
        db.session.commit()
        return jsonify({"code": 200, "msg": "发布成功待审核"})
    if closeid==2:
        talentsid = data["talentsid"]
        need = tablename1(code= code,closeid=closeid, title=title, described=described, talentsid=talentsid, money=money, userid=userid,status=1)
        db.session.add(need)
        db.session.commit()
        return jsonify({"code": 200, "msg": "发布成功待审核"})
    r.list_push("needs", code)
    return jsonify({"code": 400, "msg": "请选择计费方式"})

@need_blue.route("/sneed")
# 获取审核过的需求
def sneed():
    page = request.args.get("page")
    page_size = request.args.get("page_size")
    key = "need" + str(page)
    # r.del_key(key + "setnx")
    # 先查看缓存中是否存在
    lst = r.str_get(key)
    # 存在直接获取
    if lst:
        lists = json.loads(lst)
    # 不存在/查询数据
    else:
        lists = []
        start = (int(page) - 1) * int(page_size)
        # 并发访问同时操作数据库，解决方案分布式锁
        flag = r.str_setnx(key + "setnx", 1)
        if flag == True:
            q1 = db.session.query(Need).filter(Need.status == 2)
            q2 = db.session.query(Need1).filter(Need1.status == 2)
            q3 = db.session.query(Need2).filter(Need2.status == 2)
            ret = q1.union(q2).union(q3).offset(start).limit(page_size).all()  # 数据重复，只留一条
            for i in ret:
                lists.append({
                    'code': str(i.code),
                    'title': i.title,
                    "money": i.money,
                    "described": i.described,
                    "closeid": i.closeid,
                    "userid": i.userid
                })
            # 加入缓存
            r.str_add(key, json.dumps(lists))
            r.del_key(key + "setnx")
    need = db.session.execute("select count(code) as a  from (select * from need where status=2 union all select * from need1 where status=2 union all select * from need2 where status=2) as t")
    total = []
    for i in list(need):
        total.append(i.a)
    return jsonify({"code": 200, "msg": "获取成功", "data": lists,"total":total})

@need_blue.route("/needall")
# 全部需求
def needall():
    need = db.session.query(Need).filter()
    need1 = db.session.query(Need1).filter()
    need2 = db.session.query(Need2).filter()
    ret = need.union(need1).union(need2).all()  # 数据重复，只留一条
    lists=[]
    for i in ret:
        lists.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid
        })
    return jsonify({"code": 200, "msg": "获取成功", "data": lists})

@need_blue.route("/need_close")
# 外包/计时
def need_close():
    closeid = request.args.get("closeid")
    need = db.session.query(Need).filter(Need.closeid == closeid)
    need1 = db.session.query(Need1).filter(Need1.closeid == closeid)
    need2 = db.session.query(Need2).filter(Need2.closeid == closeid)
    ret = need.union(need1).union(need2).all()  # 数据重复，只留一条
    lists = []
    for i in ret:
        lists.append({
            'code': str(i.code),
            'title': i.title,
            "money": i.money,
            "described": i.described,
            "closeid": i.closeid,
            "userid": i.userid
        })
    return jsonify({"code": 200, "msg": "获取成功", "data": lists})

@need_blue.route('/label_index')
# 查询
def label_index():
    input = request.args.get('input')
    lst = []
    res = Need.query.filter(Need.title.ilike(f"%{input}%")).all()
    if res:
        lst.append(res)
    ress = Need1.query.filter(Need1.title.ilike(f"%{input}%")).all()
    if ress:
        lst.append(ress)
    resa = Need2.query.filter(Need2.title.ilike(f"%{input}%")).all()
    if resa:
        lst.append(resa)
    new_list = [j for i in lst for j in i]
    lists = []
    if new_list:
        for s in new_list:
            lists.append({
                'code': str(s.code),
                'title': s.title,
                "money": s.money,
                "described": s.described,
                "closeid": s.closeid,
                "userid": s.userid
            })
        return jsonify({
            'code': 200,
            'msg': "OK",
            "data":lists
        })
    else:
        return jsonify({
            'code': 400,
            'msg': "数据不存在"
        })







